/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.SABM;

import entity.establishment.Stakeholder;
import entity.establishment.OutletFood;
import entity.tx.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import managedBean.TX.Rep.EditOutletMB;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;
import session.TX.OutletSBRemote;

//Imports for primefaces maps

/**
 *
 * @author TWD
 */
@ManagedBean(name = "outletManagerBean")
@ViewScoped
public class OutletMB {

    @Resource(name = "foodsage")
    private DataSource foodsage;
    
    @EJB
    private OutletSBRemote outlet;
    private String outletName;
    private Stakeholder stakeholder;
    private String statusMessage;
    private OutletFood selectedOutlet;
    private Integer month1;
    private Integer year;
    private List<String> selectedCuisinesIDs;
    long outletId;
    private double latitude = 0, longitude = 0;
    //Data fields for creating outlet manager
    private String outletManager_email;
    private Long outletID;
    private int option=0;

    public OutletMB() {
    }

    public void generateReport(ActionEvent event) {
        outletId = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletId");
        try {
            int month = getMonth1() - 1;
            Calendar lowerBound = Calendar.getInstance();
            lowerBound.set(getYear(), month, 1);

            Calendar upperBound = Calendar.getInstance();
            int lastDayOfMonth = lowerBound.getActualMaximum(Calendar.DAY_OF_MONTH);
            upperBound.set(getYear(), month, lastDayOfMonth);

            ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();

            String lowerBound_string = "'" + getYear() + "-" + getMonth1() + "-" + lowerBound.get(Calendar.DATE) + " 00:00:00.0'";
            String upperBound_string = "'" + getYear() + "-" + getMonth1() + "-" + upperBound.get(Calendar.DATE) + " 00:00:00.0'";

            String strSQL = "SELECT TIME_STAMP AS PURCHASEDITEM_TIME_STAMP, QUANTITY AS PURCHASEDITEM_QUANTITY, ITEM_NAME AS PURCHASEDITEM_ITEM_NAME, SUBTOTAL AS PURCHASEDITEM_SUBTOTAL FROM PURCHASEDITEM"
                    + " WHERE TIME_STAMP BETWEEN " + lowerBound_string + " AND " + upperBound_string + " AND OUTLET_ID = " + outletId;

            ResultSet rsAddresses = foodsage.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsAddresses);
            InputStream reportStream = ((HttpSession) ec.getSession(true)).getServletContext().getResourceAsStream("/jasperreports/outletReport.jasper");

            ec.setResponseContentType("application/pdf");
            OutputStream outputStream = ec.getResponseOutputStream();

            JasperRunManager.runReportToPdfStream(reportStream, outputStream, new HashMap(), jrResultSetDataSource);

            outputStream.flush();
            outputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void generateReservationReport(ActionEvent event) {
        outletId = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletId");
        try {
            int month = getMonth1() - 1;
            Calendar lowerBound = Calendar.getInstance();
            lowerBound.set(getYear(), month, 1);

            Calendar upperBound = Calendar.getInstance();
            int lastDayOfMonth = lowerBound.getActualMaximum(Calendar.DAY_OF_MONTH);
            upperBound.set(getYear(), month, lastDayOfMonth);

            ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();

            String lowerBound_string = "'" + getYear() + "-" + getMonth1() + "-" + lowerBound.get(Calendar.DATE) + " 00:00:00.0'";
            String upperBound_string = "'" + getYear() + "-" + getMonth1() + "-" + upperBound.get(Calendar.DATE) + " 00:00:00.0'";

            String strSQL = "SELECT AREA_ID AS OUTLETRESERVATION_AREA_ID, CUSTOMERSHOWUP AS OUTLETRESERVATION_CUSTOMERSHOWUP, NUMPPL AS OUTLETRESERVATION_NUMPPL, TSTIME AS OUTLETRESERVATION_TSTIME, TIMESLOT AS OUTLETRESERVATION_TIMESLOT FROM OUTLETRESERVATION"
                    + " WHERE TIMESLOT BETWEEN " + lowerBound_string + " AND " + upperBound_string + " AND CONFIRMSTATUS = TRUE AND OUTLET_ID = " + outletId;

            ResultSet rsAddresses = foodsage.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsAddresses);
            InputStream reportStream = ((HttpSession) ec.getSession(true)).getServletContext().getResourceAsStream("/jasperreports/reservationReport.jasper");

            ec.setResponseContentType("application/pdf");
            OutputStream outputStream = ec.getResponseOutputStream();

            JasperRunManager.runReportToPdfStream(reportStream, outputStream, new HashMap(), jrResultSetDataSource);

            outputStream.flush();
            outputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

//    public void createOutlet(ActionEvent event) {
//        
//        //Check the lat and long
//        if(longitude < 103.593407 || longitude > 104.045219 || latitude < 1.235865 || latitude > 1.473035){
//            System.out.println("Outside boundary!");
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Please ensure the location marker is inside Singapore!", "")); 
//            return;
//        }  
//        
//        //Creating outlet
//        String outletname = String.valueOf(getOutletName());
//        String phonenumber = String.valueOf(getPhoneNumber());
//        String outletaddress = String.valueOf(getOutletAddress());
//        
//        //pull the stakeholder name from the session
//        Long stakeholderID = (Long)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderId");
//        try {
//            getOutlet().addNewOutlet_Food(stakeholderID, outletname, phonenumber, outletaddress, latitude, longitude);
//            setStatusMessage(outletName + " created successfully");
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Result: " + getStatusMessage(), ""));      
//           
//
//        } 
//        catch (ExistException eex) {
//            setStatusMessage("Error");
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Result: " + getStatusMessage(), ""));
//        } 
//        catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }
    public List<Cuisine> outletManagerViewCuisines() {
        Long outletID = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletId");
        return getCuisineByOutlet(outletID);
    }

    public List<Cuisine> getCuisineByOutlet(Long outletID) {
        return outlet.getCuisineByOutlet(outletID);
    }

    public List<Cuisine> getAllCuisines() {
        return outlet.getAllCuisines();
    }

    public void changeCuisineList() {
        Long outletID = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletId");
        outlet.changeOutletCuisine(outletID, selectedCuisinesIDs);
    }

    public List<OutletFood> getAllOutlets() {
        return getOutlet().getAllOutlets();
    }

    public List<OutletFood> getOutletsByStakeholder() {
        String stakeholderName = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderName").toString();
        return outlet.getOutletByStakeholder(stakeholderName);
    }

    public List<OutletFood> getSpecificOutlet(ActionEvent event) {
        String o = String.valueOf(outletName);
        return getOutlet().getSpecificOutlet(o);
    }

    public void deleteOutlet(OutletFood o) {
        Long outletId = o.getId();
        String outletName = o.getOutletName();
        setStatusMessage(outletName + " deleted successfully");
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Result: " + getStatusMessage(), ""));
        outlet.deleteOutlet(outletId);
    }

    public void updateFields() {
        this.outletName = selectedOutlet.getOutletName();
        //this.phoneNumber = selectedOutlet.getPhoneNo();
    }

    public List<String> getOutletManagerEmailsbyOutlet() {
        if (selectedOutlet == null) {
            return new ArrayList<String>();
        }
        outletID = selectedOutlet.getId();
        return outlet.getOutletManagerEmailsbyOutlet(outletID);
    }

    public void createOutletManager() {
        outletID = selectedOutlet.getId();
        System.out.println("OutletMB: Adding " + outletManager_email + " as a manager of outlet " + outletID);
        String statusMSG = outlet.addManagerToOutlet(outletManager_email, outletID);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMSG, ""));
        outletManager_email = "";
    }

    public void deleteOutletManager() {
        System.out.println("deleting outelt manager");
        System.out.println(outletManager_email);

        if (outletManager_email == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "No manager to delete!", ""));
            return;
        }

        outletID = selectedOutlet.getId();
        System.out.println("OutletMB: Removing " + outletManager_email + " as a manager of outlet " + outletID);
        String statusMSG = outlet.removeManagerFromOutlet(outletManager_email, outletID);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMSG, ""));
        outletManager_email = "";
    }
    
    public void updateSelectedOutlet(OutletFood o){
        System.out.println("calling update selected outlet method");
        this.selectedOutlet = o;
    }

    public String getOutletName() {
        return outletName;
    }

    public void setOutletName(String outletName) {
        this.outletName = outletName;
    }

    public Stakeholder getStakeholder() {
        return stakeholder;
    }

    public void setStakeholder(Stakeholder stakeholder) {
        this.stakeholder = stakeholder;
    }

    /**
     * @return the outlet
     */
    public OutletSBRemote getOutlet() {
        return outlet;
    }

    /**
     * @param outlet the outlet to set
     */
    public void setOutlet(OutletSBRemote outlet) {
        this.outlet = outlet;
    }

    /**
     * @return the statusMessage
     */
    public String getStatusMessage() {
        return statusMessage;
    }

    /**
     * @param statusMessage the statusMessage to set
     */
    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    /**
     * @return the selectedOutlet
     */
    public OutletFood getSelectedOutlet() {
        return selectedOutlet;
    }

    /**
     * @param selectedOutlet the selectedOutlet to set
     */
    public void setSelectedOutlet(OutletFood selectedOutlet) {
        this.selectedOutlet = selectedOutlet;
    }

    /**
     * @return the outletManager_email
     */
    public String getOutletManager_email() {
        return outletManager_email;
    }

    /**
     * @param outletManager_email the outletManager_email to set
     */
    public void setOutletManager_email(String outletManager_email) {
        this.outletManager_email = outletManager_email;
    }

    /**
     * @return the outletID
     */
    public Long getOutletID() {
        return outletID;
    }

    /**
     * @param outletID the outletID to set
     */
    public void setOutletID(Long outletID) {
        this.outletID = outletID;
    }

    /**
     * @return the latitude
     */
    public double getLatitude() {
        return latitude;
    }

    /**
     * @param latitude the latitude to set
     */
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    /**
     * @return the longitude
     */
    public double getLongitude() {
        return longitude;
    }

    /**
     * @param longitude the longitude to set
     */
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    /**
     * @return the month1
     */
    public Integer getMonth1() {
        return month1;
    }

    /**
     * @param month1 the month1 to set
     */
    public void setMonth1(Integer month1) {
        this.month1 = month1;
    }

    /**
     * @return the year
     */
    public Integer getYear() {
        return year;
    }

    /**
     * @param year the year to set
     */
    public void setYear(Integer year) {
        this.year = year;
    }

    /**
     * @return the selectedCuisinesIDs
     */
    public List<String> getSelectedCuisinesIDs() {
        return selectedCuisinesIDs;
    }

    /**
     * @param selectedCuisinesIDs the selectedCuisinesIDs to set
     */
    public void setSelectedCuisinesIDs(List<String> selectedCuisinesIDs) {
        this.selectedCuisinesIDs = selectedCuisinesIDs;
    }

    public int getOption() {
        return option;
    }

    public void setOption(int option) {
        this.option = option;
    }
    
    public void updateOption(int option){
        this.option = option;
        System.out.println(option);
    }
    
}
